<template>
  <div class="map-container">
    <div class="search-input">
      <el-autocomplete
        v-model="state.searchText"
        :fetch-suggestions="handleSearch"
        :trigger-on-focus="false"
        clearable
        placeholder="请输入关键字"
        @select="handleSelect"
        style="width: 300px"
      />
    </div>
    <div id="positionMap" class="map" style="height: 400px" />

    <div class="select-info">
      <el-descriptions
        label-class-name="custom-description-label-140"
        :column="2"
        border
        :colon="true"
      >
        <el-descriptions-item>
          <template #label>定位经度</template>
          {{ state.selectItem.longitude }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>定位纬度</template>
          {{ state.selectItem.latitude }}
        </el-descriptions-item>
        <el-descriptions-item>
          <template #label>定位详细地址</template>
          {{ state.selectItem.address }}
        </el-descriptions-item>
      </el-descriptions>
    </div>
    <div class="form-item-btn-group">
      <el-button type="default" @click="cancel">取消</el-button>
      <el-button type="primary" @click="confirm">确认</el-button>
    </div>
  </div>
</template>

<script setup>
import { shallowRef, computed, watch, ref, reactive, onMounted } from 'vue'
import areaCode from '@/components/area-cascader/areaCode.js'
import AMapLoader from '@amap/amap-jsapi-loader'
import mapObj from '@/utils/mapKey.js'
window._AMapSecurityConfig = {
  securityJsCode: mapObj.securityJsCode
}
const emit = defineEmits([
  'update:longitude',
  'update:latitude',
  'update:address',
  'cancel'
])
const props = defineProps({
  longitude: {
    type: String,
    default: ''
  },
  latitude: {
    type: String,
    default: ''
  },
  address: {
    type: String,
    default: ''
  }
})
const map = shallowRef(null)

const state = reactive({
  autoOptions: {},
  selectItem: {
    latitude: '',
    longitude: '',
    address: ''
  },
  searchText: '',
  map: null,
  marker: null,
  search: null,
  geocoder: null
})

let placeSearch, AMapObj, marker, geocoder
const initMap = () => {
  AMapLoader.load({
    key: mapObj.key, // 申请好的Web端Key，首次调用 load 时必填
    version: '2.0'
  }).then(AMap => {
    AMapObj = AMap
    map.value = new AMap.Map('positionMap', {
      //设置地图容器id
      viewMode: '3D', //是否为3D地图模式
      zoom: 15, //初始化地图级别
      center: [113.266887, 23.133306] //初始化地图中心点位置
    })
    // 添加点击事件
    map.value.on('click', onMapClick)
    if (state.selectItem.longitude) {
      drawMarker(state.selectItem.longitude,state.selectItem.latitude)
    }
    AMap.plugin(
      [
        // 'AMap.ToolBar',
        // 'AMap.Scale',
        'AMap.Geolocation',
        'AMap.PlaceSearch',
        'AMap.Geocoder'
      ],
      () => {
        // 缩放条
        // const toolbar = new AMap.ToolBar()
        // 比例尺
        // const scale = new AMap.Scale()
        // 定位
        const geolocation = new AMap.Geolocation({
          enableHighAccuracy: true, //是否使用高精度定位，默认:true
          timeout: 10000, //超过10秒后停止定位，默认：5s
          position: 'RT', //定位按钮的停靠位置
          buttonOffset: new AMap.Pixel(10, 20), //定位按钮与设置的停靠位置的偏移量，默认：Pixel(10, 20)
          zoomToAccuracy: true //定位成功后是否自动调整地图视野到定位点
        })
        geocoder = new AMap.Geocoder({
          // city: '全国'
          city: '440000'
        })
        // map.value.addControl(geolocation)
        // map.value.addControl(toolbar)
        // map.value.addControl(scale)
        placeSearch = new AMap.PlaceSearch({
          map: map.value,
          // city: '',
          city: '440000',
          pageSize: 30, // 单页显示结果条数
          pageIndex: 1, // 页码
          citylimit: false, // 是否强制限制在设置的城市内搜索
          autoFitView: true
        })
      }
    )
  })
}
onMounted(() => {
  initMap()
  state.selectItem = {
    latitude: props.latitude,
    longitude: props.longitude,
    address: props.address
  }
})
// 搜索地图
const handleSearch = (queryString, cb) => {
  console.log('queryString',queryString);
  placeSearch.search(queryString, (status, result) => {
    if (result && typeof result === 'object' && result.poiList) {
      const list = result.poiList.pois
      list.forEach(item => {
        item.value = item.name
        item.label = item.name
      })
      console.log('list',list,status, result);
      cb(list)
    } else {
      cb([])
    }
  })
}
// 点击地图
const onMapClick = e => {
  const { lng, lat } = e.lnglat
  // 逆地理编码
  geocoder.getAddress([lng, lat], (status, result) => {
    if (status === 'complete' && result.info === 'OK') {
      console.log('result.regeocode', result.regeocode)
      const { addressComponent, formattedAddress } = result.regeocode
      let { city, province, district } = addressComponent
      if (!city) {
        // 直辖市
        city = province
      }
      state.selectItem = {
        longitude: lng,
        latitude: lat,
        address: formattedAddress,
        zone: [province, city, district]
      }
      drawMarker(lng, lat)
    }
  })
}
// 点击搜索项
const handleSelect = item => {
  console.log('item', item)
  const { pname, cityname, adname, address, name } = item
  const { lng, lat } = item.location
  state.selectItem = {
    longitude: lng,
    latitude: lat,
    address: pname + cityname + adname + address,
    zone: [pname, cityname, adname],
    name
  }
  map.value.setZoomAndCenter(16, [lng, lat])
}
// 绘制地点marker
const drawMarker = (long, lat) => {
  const longitude = long
  const latitude = lat
  if (marker) {
    marker.setMap(null)
  }
  marker = new AMapObj.Marker({
    position: new AMapObj.LngLat(longitude, latitude),
    anchor: 'bottom-center'
  })
  map.value.add(marker)
  map.value.setZoomAndCenter(16, [longitude, latitude])
}

const confirm = () => {
  console.log(state.selectItem)
  emit('update:longitude', state.selectItem.longitude + '')
  emit('update:latitude', state.selectItem.latitude + '')
  emit('update:address', state.selectItem.address)
  emit('cancel')
}

const cancel = () => {
  emit('cancel')
}
</script>

<style lang="scss" scoped>
// .map-wrapper {
//   position: relative;
//   width: 100%;
//   height: 400px;
//   #positionMap {
//     width: 100%;
//     height: 100%;
//   }
//   .search-box {
//     position: absolute;
//     left: 30px;
//     top: 80px;
//     z-index: 1;
//     display: flex;
//     align-items: center;
//   }
// }
.search-input {
  position: absolute;
  left: 30px;
  top: 80px;
  z-index: 1;
  display: flex;
  align-items: center;
}
</style>
